package com.qianlou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qianlou.common.enums.ResponseStatusEnum;
import com.qianlou.common.enums.YesOrNo;
import com.qianlou.common.exception.Display;
import com.qianlou.common.result.PagedResult;
import com.qianlou.mapper.QuestionLibCustomMapper;
import com.qianlou.mapper.QuestionLibMapper;
import com.qianlou.pojo.Candidate;
import com.qianlou.pojo.Interviewer;
import com.qianlou.pojo.Job;
import com.qianlou.pojo.QuestionLib;
import com.qianlou.pojo.bo.QuestionLibBO;
import com.qianlou.pojo.vo.InitQuestionsVO;
import com.qianlou.pojo.vo.QuestionLibVO;
import com.qianlou.service.CandidateService;
import com.qianlou.service.InterviewerService;
import com.qianlou.service.JobService;
import com.qianlou.service.QuestionLibService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 面试题库表（每个数字人面试官都会对应一些面试题） 服务实现类
 * </p>
 *
 * @author James
 * @since 2025-04-26
 */
@Service
public class QuestionLibServiceImpl extends ServiceImpl<QuestionLibMapper, QuestionLib> implements QuestionLibService {

    @Resource
    private QuestionLibMapper questionLibMapper;

    @Resource
    private QuestionLibCustomMapper questionLibCustomMapper;

    @Resource
    private CandidateService candidateService;

    @Resource
    private JobService jobService;

    @Resource
    private InterviewerService interviewerService;

    @Override
    public void createOrUpdate(QuestionLibBO questionLibBO) {
        QuestionLib questionLib = new QuestionLib();
        BeanUtils.copyProperties(questionLibBO, questionLib);
        questionLib.setUpdatedTime(LocalDateTime.now());
        if (StringUtils.isBlank(questionLib.getId())) {
            questionLib.setCreateTime(LocalDateTime.now());
            questionLib.setIsOn(YesOrNo.YES.getType());
            questionLibMapper.insert(questionLib);
        } else {
            questionLibMapper.updateById(questionLib);
        }
    }

    @Override
    public PagedResult selectQuestionLibList(String aiName, String question, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        Map<String, Object> paramsMap = new HashMap<>();
        if (!StringUtils.isBlank(aiName)) {
            paramsMap.put("aiName", aiName);
        }
        if (!StringUtils.isBlank(question)) {
            paramsMap.put("question", question);
        }
        List<QuestionLibVO> questionList = questionLibCustomMapper.selectQuestionLibList(paramsMap);
        return PagedResult.of(questionList, page);
    }

    @Override
    public void display(String questionLibId, Integer isOn) {
        QuestionLib questionLib = new QuestionLib();
        questionLib.setId(questionLibId);
        questionLib.setIsOn(isOn);
        questionLibMapper.updateById(questionLib);
    }

    @Override
    public List<InitQuestionsVO> getRandomQuestions(String candidateId, Integer num) {
        //check candidate
        Candidate candidate = candidateService.getById(candidateId);
        if (candidate == null) {
            Display.throwException(ResponseStatusEnum.CANDIDATE_NOT_EXIST);
        }
        //check job
        if (StringUtils.isBlank(candidate.getJobId())) {
            Display.throwException(ResponseStatusEnum.JOB_NOT_EXIST);
        }
        Job job = jobService.getById(candidate.getJobId());
        if (job == null || YesOrNo.NO.getType().equals(job.getStatus())) {
            Display.throwException(ResponseStatusEnum.JOB_NOT_EXIST);
        }
        //check interviewer
        if (StringUtils.isBlank(job.getInterviewerId())) {
            Display.throwException(ResponseStatusEnum.INTERVIEWER_NOT_EXIST);
        }
        // get questions by interviewer
        Long questionCount = questionLibMapper.selectCount(new QueryWrapper<QuestionLib>()
                .eq("interviewer_id", job.getInterviewerId())
                .eq("is_on", YesOrNo.YES.getType())
        );
        List<Long> randomList = getRandomList(questionCount, num);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("interviewerId", job.getInterviewerId());
        List<InitQuestionsVO> questionList = new ArrayList<>();
        for (Long offset : randomList) {
            paramsMap.put("offset", offset);
            InitQuestionsVO questionsVO = questionLibCustomMapper.selectInitQuestionLimitOne(paramsMap);
            questionList.add(questionsVO);
        }
        return questionList;
    }
    private List<Long> getRandomList(Long questionCount, Integer num) {
        List<Long> indices = new ArrayList<>();
        for (long i = 0; i < questionCount; i++) {
            indices.add(i);
        }
        Collections.shuffle(indices);
        return indices.subList(0, (int) Math.min(num, questionCount));
    }
}
